package com.pgy.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pgy.backend.entity.User;
import com.pgy.backend.entity.UserLogin;
import com.pgy.backend.mapper.UserMapper;
import com.pgy.backend.service.UserService;
import com.pgy.backend.utils.JwtUtil;
import com.pgy.backend.utils.RedisCache;
import com.pgy.backend.vo.ResultData;
import com.pgy.backend.vo.ReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AuthenticationConfiguration authenticationconfiguration;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisCache redisCache;

    //
    @Override
    public ResultData login(User user) {
        //AuthenticationManager authenticationmanager进行用户认证
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(user.getName(), user.getPassword(), null);
        Authentication authenticate = null;

        try {
            authenticate = authenticationconfiguration.getAuthenticationManager().authenticate(token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }

        //获取principal 对象
        UserLogin principal = (UserLogin) authenticate.getPrincipal();
        //生成jwt
        String jwt = JwtUtil.createJWT(String.valueOf(principal.getUser().getId()));
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        //保存至redis
        redisCache.setCacheObject("login:" + principal.getUserId(), principal, JwtUtil.JWT_TTL, TimeUnit.MILLISECONDS);
        return ResultData.success("登录成功", map);

    }

    /**
     * 限定于管理员进行注册，用户不能自己注册
     *
     * @param user
     * @return
     */
    @Override
    public ResultData register(User user) {
        //查询账号是否存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, user.getId());

        User user2 = userMapper.selectOne(queryWrapper);
        if (user2 != null) {
            //判断当前手机号对应的用户是否新用户，如果是新用户自动完成创建
            return ResultData.error(ReturnCode.CODE_500.getCode(), "注册失败,账号已存在");
        }
        userMapper.save(user);
        return ResultData.success("注册成功", null);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getName, username);
        User u = userMapper.selectOne(queryWrapper);
        //权限信息的封装
        List<String> permissions = new ArrayList<>(
                Arrays.asList(u.getAdministrator().split("、")));

        return new UserLogin(u, permissions);
    }

}
